package com.sunshine.lnuplus.ui.activity

import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Looper
import android.view.KeyEvent
import android.view.LayoutInflater
import androidx.lifecycle.ViewModelProvider
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.base.BaseActivity
import com.sunshine.lnuplus.callback.LoginCallBack
import com.sunshine.lnuplus.internet.LoadLesson
import com.sunshine.lnuplus.internet.LoadScore
import com.sunshine.lnuplus.utils.CryptoUtils
import com.sunshine.lnuplus.utils.StatusBarUtils
import com.sunshine.lnuplus.utils.TagHelper
import com.sunshine.lnuplus.view.DialogWithView
import com.sunshine.lnuplus.view.DialogWithoutView
import com.sunshine.lnuplus.viewModel.LoginViewModel
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : BaseActivity() {

    private lateinit var viewModel: LoginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
        initView()
    }

    private fun initView() {
        title = "登录"
        StatusBarUtils.setStatusBarWithColor(this, color)
        if(isNight){
            textView_super.setTextColor(Color.WHITE)
            textView_appname.setTextColor(Color.WHITE)
        }
        val view = LayoutInflater.from(this).inflate(R.layout.dialog_loading, null, false)
        val loading = DialogWithView.newInstance(view, "正在登录",true, null, null)
        textView_agree.setOnClickListener {
            val positive = DialogInterface.OnClickListener { _, _ ->  }
            DialogWithoutView.newInstance("Shine课程表用户协议", resources.getString(R.string.agree), false, positive, null).show(supportFragmentManager, "agree")
        }
        val user = viewModel.getUser()
        val pw = viewModel.getPassword()
        if(user!!.isNotBlank()){
            edit_sno.setText(user)
        }
        if(pw!!.isNotBlank()){
            edit_password.setText(CryptoUtils.decrypt(pw, resources.getString(R.string.pw)))
        }
        edit_sno.setText(viewModel.getUser())

        fab_to_login.setOnClickListener {
            when {
                !checkBox_agree.isChecked -> {
                    Toasty.info(this, "请仔细阅读上方《用户协议》后勾选“同意用户协议”按钮").show()
                }
                edit_sno.text.toString().isEmpty() -> {
                    tip_sno.error = "请输入的学号"
                    tip_sno.isErrorEnabled = true
                }
                edit_password.text.toString().isEmpty() -> {
                    tip_sno.isErrorEnabled = false
                    tip_password.error = "请输入的密码"
                    tip_password.isErrorEnabled = true
                }
                else -> {
                    StatusBarUtils.hideSoftInput(this, fab_to_login)
                    loading.show(supportFragmentManager, "loading")
                    tip_password.isErrorEnabled = false
                    if(intent.getBooleanExtra("score", false)){
                        LoadScore(edit_sno.text.toString(), edit_password.text.toString(), object : LoginCallBack {
                            override fun onSuccess(){
                                Looper.prepare()
                                loading.dismiss()
                                viewModel.insertUser(edit_sno.text.toString())
                                if(checkBox_remember.isChecked){
                                    viewModel.insertPassword(CryptoUtils.encrypt(edit_password.text.toString(), resources.getString(R.string.pw)))
                                }else{
                                    viewModel.insertPassword("")
                                }
                                Toasty.success(this@LoginActivity, "登录成功", Toasty.LENGTH_SHORT).show()
                                setResult(TagHelper.LOGIN)
                                this@LoginActivity.finish()
                                Looper.loop()
                            }

                            override fun onFail(status: String) {
                                Looper.prepare()
                                loading.dismiss()
                                Toasty.error(this@LoginActivity, status, Toasty.LENGTH_SHORT).show()
                                Looper.loop()
                            }
                        })
                    }else{
                        LoadLesson(
                            viewModel.repository,
                            edit_sno.text.toString(),
                            edit_password.text.toString(),
                            object : LoginCallBack {
                                override fun onSuccess(){
                                    loading.dismiss()
                                    viewModel.insertUser(edit_sno.text.toString())
                                    if(checkBox_remember.isChecked){
                                        viewModel.insertPassword(CryptoUtils.encrypt(edit_password.text.toString(), resources.getString(R.string.pw)))
                                    }else{
                                        viewModel.insertPassword("")
                                    }

                                    setResult(TagHelper.LOGIN)
                                    this@LoginActivity.finish()
                                }

                                override fun onFail(status: String) {
                                    Looper.prepare()
                                    loading.dismiss()
                                    Toasty.error(this@LoginActivity, status, Toasty.LENGTH_SHORT).show()
                                    Looper.loop()
                                }
                        })
                    }
                }
            }
        }

        getToolBar()?.setNavigationOnClickListener {
            setResult(Activity.RESULT_CANCELED)
            supportFinishAfterTransition()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_DOWN) {
            setResult(Activity.RESULT_CANCELED)
            finish()
            true
        } else {
            super.onKeyDown(keyCode, event)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == TagHelper.LOGIN){
            when(resultCode){
                TagHelper.LOGIN -> {
                    setResult(TagHelper.LOGIN)
                    finish()
                }
                Activity.RESULT_CANCELED -> {
                    setResult(Activity.RESULT_CANCELED)
                    finish()
                }
            }
        }
    }
}
